package com.block.im.util;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.im.config.IMConfig;
import com.block.im.enums.UserTypeEnum;
import com.block.im.model.dto.IMHttpResultDTO;
import com.block.im.model.dto.IMUserInfoDTO;
import com.block.im.model.param.ImUserParam;
import com.block.im.service.IImUserSigInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 中国：console.tim.qq.com，备域名 adminapi.my-imcloud.com
 */
@Component
public class ImHttpUtil {

    private static final String REQ_URL = "https://console.tim.qq.com/{}?sdkappid={}&identifier={}&usersig={}&random={}&contenttype=json";

    @Autowired
    IMConfig imConfig;
    @Autowired
    IImUserSigInfoService imUserSigInfoService;

    public IMHttpResultDTO httpRequest(String uri, Map<String, Object> paramMap){

        IMHttpResultDTO imHttpResultDTO = new IMHttpResultDTO();
        imHttpResultDTO.setSuccess(false);
        try {

            ImUserParam imUserParam = new ImUserParam(imConfig.getAdminAccountId(), UserTypeEnum.ROOT);
            // 查询管理员信息
            IMUserInfoDTO imUserInfoDTO = imUserSigInfoService.genUserSig(imUserParam, false);
            Integer random = RandomUtil.randomInt(Integer.MAX_VALUE);

            String requestUrl =
                    StrUtil.format(REQ_URL, uri, imConfig.getSdkAppId(), imUserInfoDTO.getUserId(), imUserInfoDTO.getUserSig(), random);

            System.out.println();
            System.out.println(requestUrl);
            System.out.println();
            System.out.println(JSON.toJSONString(paramMap));
            System.out.println();


            String response = HttpUtil.createPost(requestUrl)
                    .body(JSON.toJSONString(paramMap))
                    .execute()
                    .body();

            System.out.println();
            System.out.println(response);
            System.out.println();

            JSONObject jsonObject = JSON.parseObject(response);
            String actionStatus = jsonObject.getString("ActionStatus");
            String errorInfo = jsonObject.getString("ErrorInfo");
            String errorCode = jsonObject.getString("ErrorCode");

            imHttpResultDTO.setResultObj(jsonObject);
            imHttpResultDTO.setErrorCode(errorCode);
            imHttpResultDTO.setErrorMsg(errorInfo);
            if (StrUtil.equals(actionStatus, "OK")){
                imHttpResultDTO.setSuccess(true);
            }

        }catch (Exception exception){
            exception.printStackTrace();
            imHttpResultDTO.setErrorMsg("异常："+exception.getMessage());
        }
        return imHttpResultDTO;
    }

}
